#!/usr/bin/env python3

import os
import sys
import json
import shutil
import requests
import datetime

def translate(word):
    url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null"
    key = {
        "type"       : "AUTO",
        "i"          : word,
        "doctype"    : "json",
        "version"    : "2.1",
        "keyfrom"    : "fanyi.web",
        "ue"         : "UTF-8",
        "action"     : "FY_BY_CLICKBUTTON",
        "typoResult" : "true"
    }

    response = requests.post(url, data=key)
    if response.status_code == 200:
        result = json.loads(response.text)
        return result["translateResult"][0][0]["tgt"]
    else:
        return response.status_code

def main():
    argv = sys.argv[1:]
    home = os.path.expanduser('~')

    if len(argv) == 0:
        while True:
            key = input("> ")
            value = translate(key)
            print(value)

            if key == 'q':
                break

            if not os.path.exists(home + "/.ec"):
                os.mkdir(home + "/.ec")

            if not os.path.exists(home + "/.ec/history"):
                os.mkdir(home + "/.ec/history")

            f = open(home + "/.ec/history/" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.') + key, "w")
            f.write(value)
            f.close()

    # history
    elif argv[0] == "clear":
        shutil.rmtree(home + "/.ec/history/")
    
    elif argv[0] == "history":
        if os.path.exists(home + "/.ec/history"):
            for f in os.listdir(home + "/.ec/history"):
                arr = f.split(".", - 1)
                print(arr[0], end = '\t')
                print('.' .join(arr[1:]), end = '\t')

                target = open(home + "/.ec/history/" + f, "r")
                print(target.read())
                target.close()

        else:
            print("No anything")
         
    # collect
    elif argv[0] == "add" and len(argv) > 1:
        for entry in argv[1:]:
            target = translate(entry)
            print(entry + "\t" + target)

            if not os.path.exists(home + "/.ec"):
                os.mkdir(home + "/.ec")

            if not os.path.exists(home + "/.ec/collect"):
                os.mkdir(home + "/.ec/collect")

            f = open(home + "/.ec/collect/" + entry, "w")
            f.write(target)
            f.close()

    elif argv[0] == "collect":
        if os.path.exists(home + "/.ec/collect"):
            for f in os.listdir(home + "/.ec/collect"):
                print(f, end = '\t')

                target = open(home + "/.ec/collect/" + f, "r")
                print(target.read())
                target.close()

    elif argv[0] == "del" and len(argv) > 1:
        for entry in argv[1:]:
            if os.path.exists(home + "/.ec/collect/" + entry):
                os.remove(home + "/.ec/collect/" + entry)
                print("Delete", entry, "ok!")

            else:
                print(entry, "entry does not exist!")

    # other
    elif argv[0] == "help":
        print("""\
ec(English & Chinese)           v0.1
------------------------------------
ec clear             Clear history
ec history           View history
ec add [entry...]    Add to collect
ec rcollect          View collect
ec del [entry...]    Delete entry
ec help              View help
ec [entry...]        Translation""")

    else:
        for key in argv:
            value = translate(key)
            print(key + "\t" + value)

            if not os.path.exists(home + "/.ec"):
                os.mkdir(home + "/.ec")

            if not os.path.exists(home + "/.ec/history"):
                os.mkdir(home + "/.ec/history")

            f = open(home + "/.ec/history/" + key + datetime.datetime.now().strftime('.%Y-%m-%d %H:%M:%S'), "w")
            f.write(value)
            f.close()

if __name__ == "__main__":
    main() 
